﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NoORM.Core;
using NoORM.Core.Service;
using NoORM.Core.Contract;
using Microsoft.Extensions.Options;
using NoORM.Core.DbAcceess;

namespace Restsql.Api.Controllers
{
    /// <summary>
    /// 删除一条数据
    /// </summary>
    [Route("{database}/{table}.[controller]")]
    [ApiController]
    public class DeleteController : ControllerBase
    {
        /// <summary>
        /// 曾删改查的服务类对象
        /// </summary>
        private readonly CrudService service;


        /// <summary>
        /// 数据库连接字符串配置
        /// </summary>
        private readonly Dictionary<string, ConnectionStringConfig> configs;

        public DeleteController(IOptions<Dictionary<string, ConnectionStringConfig>> configsOption, CrudService service)
        {
            this.configs = configsOption.Value;
            this.service = service;
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        /// <param name="database">数据库名称，忽略大小写</param>
        /// <param name="table">表名，大小写是否敏感取决于你使用的数据库产品及其配置</param>
        /// <param name="request">sql请求</param>
        /// <returns></returns>

        [HttpDelete]
        public async Task<JsonResult> Delete(string database, string table, [FromBody] SqlRequest request)
        {
            ApiData<int> apiData = new ApiData<int>();
            apiData.ServerReceiveTime = DateTime.Now;
            var query = this.configs.Where(kv => kv.Key.Equals(database, StringComparison.CurrentCultureIgnoreCase));
            if (query == null || !query.Any())
            {
                apiData.Success = false;
                apiData.Message = "没有这个数据库";
                apiData.ServerSendTime = DateTime.Now;
                return new JsonResult(apiData);
            }
            if (request.Queries == null || !request.Queries.Any())
            {
                apiData.Success = false;
                apiData.Message = "服务端拒绝无条件的delete操作";
                apiData.ServerSendTime = DateTime.Now;
                return new JsonResult(apiData);
            }

            ConnectionStringConfig config = query.First().Value;
            try
            {
                apiData.Data = await this.service.DeleteAsync(config, table, request.Queries);
                apiData.Success = true;//即使没有删除任何数据也认为是正确的，客户端要综合Success和Data两个字段来判断是否有数据被删除
            }
            catch (Exception ex)
            {
                apiData.Success = false;
                apiData.Message = ex.Message;
            }
            apiData.ServerSendTime = DateTime.Now;
            return new JsonResult(apiData);
        }

    }

}
